<template>
  <el-dialog :title="isLogin?'登录':'注册'" :visible.sync="visible" v-if="visible">
    <el-form :model="formData" :rules="rules" ref="formData" label-position="right" label-width="80px">
      <el-form-item label="手机号" prop="phone">
        <el-input placeholder="手机号" v-model="formData.phone"/>
      </el-form-item>
      <el-form-item label="验证码" prop="code" v-if="!isLogin">
        <el-input placeholder="验证码" v-model="formData.code">
          <template slot="append">
            <el-button :disabled="disabled" @click="sendMsg">{{ btnMsg }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input placeholder="密码" show-password v-model="formData.password"/>
      </el-form-item>
      <template v-if="!isLogin">
      <el-form-item label="确认密码" prop="confirmPwd">
        <el-input placeholder="确认密码" show-password v-model="formData.confirmPwd"/>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input placeholder="昵称" v-model="formData.nickname"/>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="formData.sex">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
          <el-radio :label="3">未知</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload :action="uploadUrl"  :file-list="fileList" list-type="picture-card" :limit="1" ref="avatarUpload" :on-success="uploadSuccess" :on-exceed="onExceed" :before-upload="beforeUpload">
          <i class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img :src="file.url" alt="" class="el-upload-list__item-thumbnail"/>
            <div class="el-upload-list__item-actions">
            <span @click="showImageDialog(file)">
              <i class="el-icon-zoom-in"></i>
            </span>
              <span @click="removeImage(file)">
              <i class="el-icon-delete"></i>
            </span>
            </div>
          </div>
        </el-upload>
      </el-form-item>
      </template>
      <el-form-item>
        <template v-if="isLogin">
          <el-button type="primary" @click="login">登录</el-button>
          没有账号?
          <el-button type="text" @click="isLogin = false">注册</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="register">注册</el-button>
          已有账号，去
          <el-button type="text" @click="isLogin = true">登录</el-button>
        </template>
      </el-form-item>
    </el-form>
    <el-dialog append-to-body title="查看图片" :visible.sync="showImage" v-if="showImage">
      <div style="height: 100%;width: 100%;display: flex;align-items: center;justify-content: center;">
        <img :src="showImageSrc" alt="" style="display: block;max-height: 100%;max-width: 100%">
      </div>
    </el-dialog>
  </el-dialog>

</template>

<script>
import { uuid } from 'vue-uuid'
const formData = {
  phone: '',
  nickname: '',
  password: '',
  confirmPwd: '',
  sex: 1,
  avatar: '',
  code: '',
  uuid: ''
}

export default {
  name: 'LoginView',
  data () {
    return {
      isLogin: true,
      formData: {
        ...formData
      },
      visible: false,
      rules: {
        phone: [{
          required: true,
          message: '手机号不能为空',
          trigger: 'blur'
        }, {
          patter: /^1\d{10}$/,
          message: '手机号格式错误',
          trigger: 'blur'
        }],
        nickname: [{
          required: true,
          message: '昵称不能为空',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '密码不能为空',
          trigger: 'blur'
        }],
        confirmPwd: [{
          required: true,
          message: '请再次输入密码',
          trigger: 'blur'
        }, {
          validator: (rule, value, callback) => {
            if (value !== this.formData.password) {
              callback(new Error('两次密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '验证码不能为空',
          trigger: 'blur'
        }],
        avatar: [{
          required: true,
          message: '请上传头像',
          trigger: 'blur'
        }]
      },
      uploadUrl: `${process.env.VUE_APP_BASE_URL}api/upload`,
      fileList: [],
      showImage: false,
      showImageSrc: '',
      btnMsg: '发送短信',
      disabled: false
    }
  },
  watch: {
    isLogin () {
      this.formData = { ...formData, uuid: uuid.v4() }
      this.$refs.formData.resetFields()
    }
  },
  methods: {
    init () {
      this.visible = true
      this.isLogin = true
      this.formData = {
        ...formData,
        uuid: uuid.v4()
      }
    },
    uploadSuccess (res) {
      if (res.code === 200) {
        this.formData.avatar = res.data
      } else {
        this.$message.error(res.msg)
      }
    },
    onExceed () {
      this.$message.error('请先删除原图片')
    },
    beforeUpload (file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      if (!isImage) {
        this.$message.error('请选择正确的格式！')
      }
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('文件大小不能超过20M！')
      }

      return isImage && isLt20M
    },
    showImageDialog (file) {
      this.showImage = true
      this.showImageSrc = file.url
    },
    removeImage (file) {
      this.$refs.uploadImage.handleRemove(file)
      this.formData.avatar = ''
    },
    sendMsg () {
      if (this.formData.phone) {
        this.$http.get('api/msg', { phone: this.formData.phone, uuid: this.formData.uuid }).then(() => {
          this.$message.success('发送成功')
          let time = 59
          const inter = setInterval(() => {
            time--
            if (time === 0) {
              clearInterval(inter)
              this.btnMsg = '发送短信'
              this.disabled = false
            } else {
              this.btnMsg = `${time}秒后重试`
              this.disabled = true
            }
          }, 1000)
        })
      } else {
        this.$message.error('请输入手机号')
      }
    },
    register () {
      this.$refs.formData.validate(valid => {
        if (valid) {
          this.$http.post('api/register', this.formData).then(() => {
            this.$alert('注册成功，请登录！', { type: 'success' }).then(() => {
              this.isLogin = true
            })
          })
        }
      })
    },
    login () {
      this.$refs.formData.validate(valid => {
        if (valid) {
          this.$http.post('api/login', { username: this.formData.phone, password: this.formData.password }).then(({ data }) => {
            this.$message.success('登录成功')
            this.visible = false
            sessionStorage.setItem('vipInfo', JSON.stringify(data))
            this.$emit('closeDialog')
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
